package com.lsp.java.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 定义数据库连接工具
 */
public class DBUtil {

    //初始化数据库连接信息
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql:///mango";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static ThreadLocal<Connection> connContainer = new ThreadLocal<Connection>();

    private static ComboPooledDataSource dataSourcePool = new ComboPooledDataSource();

    private static Connection connection;

    public static Connection getConnection() {
        connection = connContainer.get();
        try {
            if (null == connection) {
                Class.forName(DRIVER);
                connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connContainer.set(connection);
        }
        return connection;
    }

    public static void closeConnection() {
        Connection conn = connContainer.get();
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connContainer.remove();
        }
    }

    //c3p0 连接池管理数据库连接
    public static Connection getPoolConnection() {
        try {
            dataSourcePool.setDriverClass(DRIVER);
            dataSourcePool.setJdbcUrl(URL);
            dataSourcePool.setUser(USERNAME);
            dataSourcePool.setPassword(PASSWORD);
            dataSourcePool.setMinPoolSize(2);
            dataSourcePool.setMaxPoolSize(10);
            dataSourcePool.setAcquireIncrement(3);
            connection = dataSourcePool.getConnection();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}
